package Threaddemo.thread_0910;

import java.util.PriorityQueue;

class MyTimerTask2 implements Comparable<MyTimerTask2>{
    private Runnable runnable;
    private long time;

    public MyTimerTask2(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = time;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask2 o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer2 {
    private PriorityQueue<MyTimerTask2> priorityQueue = new PriorityQueue<>();
    private Object locker = new Object();
    public void shcedule(Runnable runnable, long delay) {
        synchronized (locker) {
            priorityQueue.offer(new MyTimerTask2(runnable,System.currentTimeMillis() + delay));
            locker.notify();
        }

    }

    public MyTimer2() {
        Thread thread = new Thread(()-> {
            while (true) {
                try {
                    synchronized (locker) {
                        while (priorityQueue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask2 myTimerTask2 = priorityQueue.peek();
                        if (myTimerTask2.getTime() <= System.currentTimeMillis()) {
                            myTimerTask2.getRunnable().run();
                            priorityQueue.poll();
                        }else {
                            locker.wait(myTimerTask2.getTime() - System.currentTimeMillis());
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.start();
    }
}


public class demo4_0516 {
    public static void main(String[] args) {
        MyTimer2 myTimer2 = new MyTimer2();
        myTimer2.shcedule(()->{
            System.out.println("1000");
        },1000);
        myTimer2.shcedule(()->{
            System.out.println("2000");
        },2000);
        myTimer2.shcedule(()->{
            System.out.println("3000");
        },3000);
    }
}

